﻿using System.Collections.Generic;
using System.Linq;
using OpenRasta.Web;
using umbraco.cms.businesslogic.web;

namespace uREST.CMS.Extensions
{
    public static class DocumentExtensions
    {
        public static Resources.Document ToResource(this Document doc)
        {
            var resource = new Resources.Document
            {
                Id = doc.Id,
                Href = typeof(Resources.Document).CreateUri("Document", new { id = doc.Id }).ToString(),
                ParentId = doc.ParentId,
                ParentHref = doc.ParentId > 0 ? typeof(Resources.Document).CreateUri("Document", new { id = doc.ParentId }).ToString() : "",
                Name = doc.Text,
                DocTypeAlias = doc.ContentType.Alias,
                HasChildren = doc.HasChildren,
                ChildrenHref = doc.HasChildren ? typeof(List<Resources.Document>).CreateUri("DocumentList", new { parentId = doc.Id }).ToString() : "",
                IsPublished = doc.Published,
                ReleaseDate = doc.ReleaseDate,
                ExpireDate = doc.ExpireDate
            };

            foreach (var property in doc.GenericProperties)
            {
                resource.Properties.Add(new Resources.Property
                {
                    Key = property.PropertyType.Alias,
                    Value = property.Value == System.DBNull.Value ? null : property.Value
                });
            }

            return resource;
        }

        public static List<Resources.Document> ToResourceList(this Document[] docs)
        {
            return new List<Document>(docs).ToResourceList();
        }

        public static List<Resources.Document> ToResourceList(this List<Document> docs)
        {
            var resourceList = new List<Resources.Document>();
            resourceList.AddRange(docs.Select(doc => doc.ToResource()));
            return resourceList;
        }

        public static Document FindAncestorByDocTypeAlias(this Document doc, string docTypeAlias)
        {
            Document ancestor = null;
            Document currentDoc = doc;

            while (currentDoc.ParentId > 0)
            {
                var parent = new Document(currentDoc.ParentId);
                if(parent.ContentType.Alias == docTypeAlias)
                {
                    ancestor = parent;
                    break;
                }

                currentDoc = parent;
            }

            return ancestor;
        }
    }
}
